package com.yuyue.springFramework.note17.examp2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 持久化类
 */
@Component
public class AnnoPersonDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //插入方法
    public int insertTable(Person person){
        return jdbcTemplate.update("insert into person(name, age, sex, id) values (?, ?, ?, ?)"
                ,person.getName(),person.getAge(),person.getSex(),person.getId());
    }

    //更新方法
    public int updateTable(Person person) {
        return jdbcTemplate.update("update person set name = ?, age = ?, sex = ? where id = ?"
                ,person.getName(),person.getAge(),person.getSex(),person.getId());
    }

    //删除方法
    public int deleteTable(Person person) {
        return jdbcTemplate.update("delete from person where id = ?"
                , person.getId());
    }

    //查询单个对象方法
    public Person queryForObject(Person person) {
        //使用Spring提供的行映射器填充对象
        return jdbcTemplate.queryForObject("select * from person where id = ?",
                new BeanPropertyRowMapper<>(Person.class), person.getId());
    }

    //查询单个对象方法
    public List<Map<String, Object>> queryOneObjectList(String id) {
        //用list避免无记录报错
        return jdbcTemplate.queryForList("select * from person where id = ?",
                 id);
    }
}
